package io.github.libkodi.basic_gateway.context;

import java.util.HashMap;

public class CurrentThread {

//	private Context ctx;
	private ThreadLocal<HashMap<String, Object>> data = new ThreadLocal<HashMap<String, Object>>();

	public CurrentThread(Context ctx) {
//		this.ctx = ctx;
	}
	
	public Thread instance() {
		return Thread.currentThread();
	}
	
	public long getThreadId() {
		return instance().getId();
	}

	public String getThreadName() {
		return instance().getName();
	}
	
	private CurrentThread setValue(String key, Object value) {
		HashMap<String, Object> map = data.get();
		
		if (map == null) {
			map = new HashMap<String, Object>();
			data.set(map);
		}
		
		map.put(key, value);
		
		return this;
	}
	
	public CurrentThread setString(String key, String value) {
		return setValue(key, value);
	}
	
	public CurrentThread setInteger(String key, int value) {
		return setValue(key, value);
	}
	
	public CurrentThread setDouble(String key, double value) {
		return setValue(key, value);
	}
	
	public CurrentThread setFloat(String key, float value) {
		return setValue(key, value);
	}
	
	public CurrentThread setLong(String key, long value) {
		return setValue(key, value);
	}
	
	public CurrentThread setBoolean(String key, boolean value) {
		return setValue(key, value);
	}
	
	public CurrentThread setObject(String key, Object value) {
		return setValue(key, value);
	}
	
	private Object getValue(String key) {
		HashMap<String, Object> map = data.get();
		
		if (map != null) {
			return map.get(key);
		}
		
		return null;
	}
	
	public String getString(String key) {
		return (String) getValue(key);
	}
	
	public int getInteger(String key) {
		return (int) getValue(key);
	}
	
	public float getFloat(String key) {
		return (float) getValue(key);
	}
	
	public double getDouble(String key) {
		return (double) getValue(key);
	}
	
	public long getLong(String key) {
		return (long) getValue(key);
	}
	
	public boolean getBoolean(String key) {
		return (boolean) getValue(key);
	}
	
	@SuppressWarnings("unchecked")
	public <T> T getObject(String key, Class<T> cls) {
		return (T) getValue(key);
	}
	
	public CurrentThread remove(String key) {
		HashMap<String, Object> map = data.get();
		
		if (map != null) {
			map.remove(key);
		}
		
		return this;
	}
	
	public void release() {
		if (data.get() != null) {
			data.remove();
		}
	}
}
